import Vue from 'vue'
import Router from 'vue-router'
import Cookies from "js-cookie"
// 电脑端页面
import login from '@/views/Login'
import register from '@/views/Register'
import adminpage from '@/views/AdminPage'
import errpage from '@/views/404'
import mypage from '@/views/MyPage'
// 手机端页面
import loginm from '@/views/mobile/Loginm'
import registerm from '@/views/mobile/Registerm'
import mypagem from '@/views/mobile/MyPagem'

Vue.use(Router)

export const router = new Router({
  mode:'history',
  routes: [
    {
      path: "/",
      redirect: "/login",
      meta: {
        roles: ['annoym', 'user', 'super']  //限定只有哪些角色才能访问
      }
    },
    {
      path: '/login',
      name: 'login',
      meta: {
        roles: ['annoym', 'user', 'super']
      },
      component: login
    },
    {
      path: '/register',
      name: 'register',
      meta: {
        roles: ['annoym', 'user', 'super']
      },
      component: register
    },
    {
      path: '/mypage',
      name: 'mypage',
      meta: {
        roles: ['user', 'super']
      },
      component: mypage
    },
    {
      path: '/adminpage',
      name: 'adminapge',
      meta: {
        roles: ['user', 'super']  // 判断是否是管理员
      },
      component: adminpage
    },

    {
      path: '/error',
      name: '404page',
      meta: {
        roles: ['annoym', 'user', 'super']
      },
      component: errpage
    },
    //  下方是手机端页面
    {
      path: '/loginm',
      name: 'loginm',
      meta: {
        roles: ['annoym', 'user', 'super']
      },
      component: loginm
    },
    {
      path: '/registerm',
      name: 'registerm',
      meta: {
        roles: ['annoym', 'user', 'super']
      },
      component: registerm
    },
    {
      path: '/mypagem',
      name: 'mypagem',
      meta: {
        roles: ['user', 'super']
      },
      component: mypagem
    },
    { // 最后就是 404 啦
      path: "*",
      redirect: "/error",
      meta: {
        roles: ['annoym', 'user', 'super']  //限定只有哪些角色才能访问
      }
    }

  ]
})
if (Cookies.get('role') === undefined) {
  Cookies.set('role', 'annoym')
}

router.beforeEach((to, from, next) => {
  if (to.meta.roles.includes(Cookies.get('role'))) {
    let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
    if (to.path === '/login' && flag) {
      next({path: '/loginm'})
    }
    if (to.path === '/register' && flag) {
      next({path: '/registerm'})
    }
    if (to.path === '/mypage' && flag) {
      next({path: '/mypagem'})
    }
    if (to.path === '/' && flag) {
      next({path: '/loginm'})
    }
    next()
  } else {
    next({path: '/error'})
  }
})
